#!/usr/bin/ruby
# vi:ft=ruby
# 此脚本处理POST请求，接受用户发表的评论，并存入数据库

require 'cgi'
require 'rubygems'
require 'active_support'
require 'active_record'

ActiveRecord::Base.establish_connection(
    :adapter => 'mysql',
    :database => 'hhac',
    :username => 'hhac',
    :password => 'iamharmless',
    :host => 'localhost')

class Comment < ActiveRecord::Base
end

class Session < ActiveRecord::Base
end

cgi = CGI.new
sessid = cgi.cookies["_session_id"]
movie = cgi["movie"]
content = cgi["comment"]

session = Session.find :first, :conditions => {:sessid => sessid}
user_id = session ? session.user_id : 0

# CGI response
puts "Content-Type: text/plain\n\n"

exit unless user_id

comment = Comment.create(
  "owner" => user_id,
  "movie" => movie,
  "content" => content
)

puts comment.to_json
